package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.common.constant.WxWithdrawal;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyWithdrawalSetupMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.AppWxWithdrawalUtils.WXPayRequest;
import com.eco.fanliapp.utils.AppWxWithdrawalUtils.WXPayUtil;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.MessageUtils;
import com.eco.fanliapp.utils.UUIDUtils;
import com.eco.fanliapp.vo.AppRequestParams.WxPayRequestParams;
import com.eco.fanliapp.vo.wechat.menu.Menu;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * app微信提现
 */
@Service
public class AppWxWithdrawalServiceImpl implements IAppWxWithdrawalService {

    private static final Logger log = LoggerFactory.getLogger(AppWxWithdrawalServiceImpl.class);

    @Autowired
    private SyWithdrawalSetupMapper syWithdrawalSetupMapper;

    @Autowired
    private WXPayRequest wxPayRequest;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private IAppWithdrawalService iAppWithdrawalService;

    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private IAppWithdrawalService withdrawalService;

    @Autowired
    private ISyUserWxContrastService iSyUserWxContrastService;

    @Autowired
    private IAppUserRedRewardService iAppUserRedRewardService;

    @Autowired
    private ISyUserWxContrastService syUserWxContrastService;

    @Autowired
    private IAppPayMethodService appPayMethodService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private ISyBlacklistService iSyBlacklistService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;

    @Autowired
    private ISyBlacklistService syBlacklistService;

    @Autowired
    private IAppUserOrderService appUserOrderService;

    /**
     * 删除菜单
     * @param accessToken
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse deleteMenu(String accessToken) throws Exception {
        return null;
    }

    /**
     * 查询菜单
     * @param accessToken
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse getMenu(String accessToken) throws Exception {
        return null;
    }

    /**
     * 创建菜单
     * @param menu
     * @param accessToken
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse createMenu(Menu menu, String accessToken) throws Exception {
        //1.准备POST请求参数
        String jsonString = JSON.toJSONString(menu);
        log.info("菜单"+ jsonString);

        //2.拼装创建菜单的url
        String url=WechatConfig.CREATE_MENU_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求，获取返回结果
        net.sf.json.JSONObject jsonObject = WeixinUtil.doPostStr(url, jsonString);
        log.info("jsonObject:"+jsonObject.toString());


        if (null != jsonObject) {
            //5.错误消息处理
            if (0 != jsonObject.getInt("errcode")) {

                int errCode = jsonObject.getInt("errcode");
                String errMsg = jsonObject.getString("errmsg");
                return ServerResponse.createByErrorMessage("error code:"+errCode+", error message:"+errMsg);
            } else {
                log.info("菜单创建成功！");
                return ServerResponse.createBySuccessMessage("菜单创建成功");
            }
        }else{

            return ServerResponse.createByErrorMessage("微信无响应结果！");
        }
    }

    /**
     * 获取accessToken
     * @return
     */
    @Override
    public String getAccessToken() throws IOException {
        //从redis中获取
        String accessToken =(String)redisTemplate.opsForValue().get("access_token");
        log.info("从redis中获取的accessToken" + accessToken);
        if(accessToken == null || "".equals(accessToken) ){
            //生成新的access_token
            accessToken = WeixinUtil.getAccessToken();
            log.info("新生成的的accessToken" + accessToken);
            redisTemplate.opsForValue().set("access_token",accessToken, 3600, TimeUnit.SECONDS);
            log.info("将accessToken存入到redis中" + accessToken);
        }
        return accessToken;
    }
    //该方法支持到2.3.0以下
//    @Override
//    public ServerResponse toGet(String amount, Long userid,Integer type) {
//        AppUser appUser = iAppUserService.selectAppUserByUserId(userid);
//        if(StringUtils.isEmpty(appUser))return ServerResponse.createByErrorMessage("无此用户信息！");
//        Long userId = appUser.getUserId();
//        log.info("============微信提现开始用户id：{}提现金额：{} ========",userId,amount);
//        //一 ：参数校验 1 校验openid是否存在  2 校验金额是否超出提现金额
//        //根据用户id查询openid
//        Object cheackResult = cheackUserAndAmount(amount,appUser);
//        if( cheackResult instanceof ServerResponse){
//            log.info("微信提现参数校验结果：{}", JSONObject.toJSONString(cheackResult));
//            return (ServerResponse) cheackResult;
//        }
//        //判断app提现是否为黑名单用户提现
//        if((type == 1 && checkBlacklist(appUser,amount)) || (type == 2 && iSyBlacklistService.userCheck(userId,appUser.getSuperInviteCode()))){
//            return  ServerResponse.createBySuccessMessage("提现正在审核中。。。请耐心等待。。。");
//        }
//        //判断是否是微信公众号提现
//        String  des;
//        AppWithdrawal oneAppWithdrawal = null;
//        log.info("区分提现的方式：" + type);
//        if(type == 2){
//            //查询提现金额
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id",userId);
//            queryWrapper.eq("applicant_status",1);
//            List<AppWithdrawal> appWithdrawalList = withdrawalService.list(queryWrapper);
//            if(StringUtils.isEmpty(appWithdrawalList) || appWithdrawalList.size() > 1) return ServerResponse.createByErrorMessage("公众号提现未找到未处理的提现记录/存在多条！");
//            oneAppWithdrawal = appWithdrawalList.get(0);
//            des = "公众号提现";
//            int intValue = oneAppWithdrawal.getAmount().intValue();
//            amount = String.valueOf(intValue);
//            log.info("输出提现金额：" + amount);
//        }else {
//            des = "省鸭APP提现";
//        }
//        String openid = (String) cheackResult;
//        //二 ：调用企业支付接口进行提现
//        //1.创建微信企业支付请求参数
//        WxPayRequestParams wxPayRequestParams = new WxPayRequestParams();
//        //2.填充请求参数
//        BigDecimal bigDecimal1 = new BigDecimal(amount);
//        BigDecimal multiply = bigDecimal1.multiply(new BigDecimal("100"));
//        wxPayRequestParams.setAmount(multiply.toString());//金额 *100
//        wxPayRequestParams.setOpenid(openid);//用户的openid（从用户表中获取）
//        //wxPayRequestParams.setRe_user_name("张三");//真实姓名（从用户表中获取）
//        wxPayRequestParams.setDesc(des);//企业付款备注
//        String partnerTradeNo = creatPartnerTradeNo(userId, amount);
//        wxPayRequestParams.setPartner_trade_no(partnerTradeNo);//订单号
//        //3.请求参数转成xml
//        String xmlStr;
//        try {
//            Map map = JSON.parseObject(JSON.toJSONString(wxPayRequestParams), HashMap.class);
//            xmlStr = WXPayUtil.generateSignedXml(map,WxWithdrawal.key);
//        } catch (Exception e) {
//            return ServerResponse.createByErrorMessage("参数转换错误！");
//        }
//        log.info("请求微信支付接口参数：{}",xmlStr);
//        String uuid = UUIDUtils.getUUID();
//        //调用支付接口
//        String wxPayResultXml;
//        try {
//            wxPayResultXml = wxPayRequest.requestWithCert(WxWithdrawal.urlSuffix, uuid, xmlStr, true);
//            //wxPayResultXml = getRestTemplate("https://" +WxWithdrawal.doMain + WxWithdrawal.urlSuffix, xmlStr);
//        } catch (Exception e) {
//            log.info("请求微信支付接口错误{}",e.getMessage());
//            return ServerResponse.createByErrorMessage("支付失败！请求微信接口错误");
//        }
//        log.info("请求微信支付接口结果{}"+wxPayResultXml);
//        Map<String, String> stringStringMap = null;
//        String wxPayResultJson = "微信支付map转json异常";
//        try {
//            stringStringMap = WXPayUtil.xmlToMap(wxPayResultXml);
//            wxPayResultJson = JSON.toJSONString(stringStringMap);
//        } catch (Exception e) {
//            log.info("微信结果参数转换异常{}",e.getMessage());
//        }
//
//        String return_code = MapUtils.getString(stringStringMap, "return_code");
//        String result_code = MapUtils.getString(stringStringMap, "result_code");
//        if (!StringUtils.isEmpty(stringStringMap) && "SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
//            int i = iSyUserMoneyService.wxPaySuccessUpdate(userId,amount);
//            log.info("更新用户金额表微信可提现结果{}用户id{}金额{}",i,userId,amount);
//            addAppWithdrawal(appUser,amount,2,"成功",wxPayResultJson,partnerTradeNo,oneAppWithdrawal);//增加提现记录
//            log.info("============微信提现结束return_code：{}   result_code：{}========",return_code,result_code);
//            //成功公众号发消息
//            try {
//                String amount1 = amount + "元";
//                ServerResponse<String> respone = sendCashMessage(appUser,"30001", appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(),amount1, "微信");
//                log.info("公众号发消息结果{}",JSON.toJSONString(respone));
//            }catch (Exception e){
//                log.info("公众号发消息异常{}",e.getMessage());
//            }
//            return ServerResponse.createBySuccessMessage("微信提现成功");
//        }
//        log.info("============微信提现结束return_code：{}result_code：{}========",return_code,result_code);
//        String return_msg = MapUtils.getString(stringStringMap, "return_msg");
//        String err_code_des = MapUtils.getString(stringStringMap, "err_code_des");
//        addAppWithdrawal(appUser,amount,3,"失败",wxPayResultJson,partnerTradeNo,oneAppWithdrawal);
//        return ServerResponse.createByErrorMessage("微信提现失败！"+return_msg+"  "+err_code_des);
//    }

    /**
     * 提现记录
     * @param amount 金额
     * @param userid 用户id
     * @param type 类型 1 app提现  2 公众号提现
     * @return
     */
    @Override
    public ServerResponse toGet(String amount, Long userid,Integer type) throws Exception{
        //==============《锁机制》=========
        //redis锁-时间 (3秒)
        long startTimes = System.currentTimeMillis() + 1000 * 60;
        //获取锁
        if (!redisLockService.lock( "user_money_zfb_lock_" + userid, startTimes + "")) {
            log.info("用户userid{}提现过去频繁",userid);
            return ServerResponse.createByErrorMessage("提现过于频繁！");
        }

        //校验用户是否有效
        AppUser appUser = iAppUserService.selectAppUserByUserId(userid);
        if(StringUtils.isEmpty(appUser)){
            log.info("校验》》无此用户信息");
            return ServerResponse.createByErrorMessage("无此用户信息！");
        }
        //=========校验是否在黑名单
        boolean userCheck = syBlacklistService.verifyUserAgreement(userid);
        if(userCheck){
            log.info("用户userid{}存在黑名单中",userid);
            return ServerResponse.createByErrorMessage("账户问题，请联系客服！");
        }
        //=========校验是否购买过商品，免单不算
        Integer orderCheck = appUserOrderService.getOrderCountNumber(userid);
        if(orderCheck == 0){
            log.info("用户除去免单未购买",userid);
            return ServerResponse.createByErrorMessage("您还没有订单，购买后可提现！");
        }

        //=========参数校验========
        //校验提现类型不能为空 1：app; 2:公众号
        if(type == null){
            log.info("校验》》提现类型不能为空");
            return ServerResponse.createByErrorMessage("提现类型不能为空");
        }
        //校验是否关注公众号
        SyUserWxContrast syUserWxContrast = iSyUserWxContrastService.selectByUserId(appUser.getWechatUnionid());
        if(StringUtils.isEmpty(syUserWxContrast) || StringUtils.isEmpty(syUserWxContrast.getWxOpendId())){
            log.info("校验》》您未关注公众号！");
            return ServerResponse.createByErrorMessage("您未关注公众号！");
        }
        //用户openId
        String wxOpendId = syUserWxContrast.getWxOpendId();
        //===========《校验金额相关》========
        ServerResponse serverResponse1 = checkPayMoney(amount,userid);
        if(serverResponse1.getStatus() != 200 ){
            return  serverResponse1;
        }

        //查询是否有未处理提现
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",appUser.getUserId());
        queryWrapper.eq("applicant_status",1);
        queryWrapper.eq("withdrawal_type",2);//微信
        List<AppWithdrawal> appWithdrawalList = withdrawalService.list(queryWrapper);
        if(CollectionUtils.isEmpty(appWithdrawalList)){
        }else {
            log.info("已有提现，暂时无法提现！");
            return ServerResponse.createByErrorMessage("已有未处理提现记录，暂时无法提现！！");
        }
        //获取用户账户
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userid);

        return appPayMethodService.dealWxPayMoney(syUserMoney, userid, amount, appUser, wxOpendId, type);

    }

//    @Transactional(rollbackFor = Exception.class)
//    public ServerResponse dealWxPayMoney(SyUserMoney syUserMoney, Long userid, String amount, AppUser appUser, String wxOpendId, int type)  throws Exception{
//
//        //======《添加日志》======
//        //添加账户变更日志
//        addSyserMoneyLog(syUserMoney, userid, amount);
//        //区分公众号与app提现方式（公众号该记录已经存在)
//
////        addAppWithdrawalNew(appUser, amount);
//        //更新用户微信账户余额(SyUserMoney)
//        int i = iSyUserMoneyService.wxPaySuccessUpdate(userid, amount);
//        log.info("更新用户金额表微信可提现结果{}用户id{}金额{}", i, userid, amount);
//        //支付失败，手动抛出异常
//        //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
//        //=============《提现》==========
//        //ServerResponse serverResponse2 = handlerPayMoney(amount, appUser, wxOpendId, type);
//        //return serverResponse2;
//        //1.创建微信企业支付请求参数
//        WxPayRequestParams wxPayRequestParams = new WxPayRequestParams();
//
//        //2.填充请求参数
//        BigDecimal bigDecimal1 = new BigDecimal(amount);
//        BigDecimal multiply = bigDecimal1.multiply(new BigDecimal("100"));//金额单位为分
//        wxPayRequestParams.setAmount(multiply.toString());//金额 *100
//        wxPayRequestParams.setOpenid(wxOpendId);//用户的openid（从用户表中获取）
//        //wxPayRequestParams.setRe_user_name("张三");//真实姓名（从用户表中获取）
//        wxPayRequestParams.setDesc(type==1?"省鸭APP提现":"公众号提现");//企业付款备注
//        String partnerTradeNo = creatPartnerTradeNo(appUser.getUserId(), amount);
//        wxPayRequestParams.setPartner_trade_no(partnerTradeNo);//订单号
//
//        //3.请求参数转成xml
//        Map map = JSON.parseObject(JSON.toJSONString(wxPayRequestParams), HashMap.class);
//        String xmlStr = WXPayUtil.generateSignedXml(map,WxWithdrawal.key);
//        log.info("请求微信支付接口参数：{}",xmlStr);
//        String uuid = UUIDUtils.getUUID();
//
//        //4.调用支付接口
//        String  wxPayResultXml = wxPayRequest.requestWithCert(WxWithdrawal.urlSuffix, uuid, xmlStr, true);
//        log.info("请求微信支付接口结果{}"+wxPayResultXml);
//
//        //5.格式化返回结果
//        Map<String, String> stringStringMap =  WXPayUtil.xmlToMap(wxPayResultXml);
//        String wxPayResultJson = JSON.toJSONString(stringStringMap);
//
//        String return_code = MapUtils.getString(stringStringMap, "return_code");
//        String result_code = MapUtils.getString(stringStringMap, "result_code");
//
//        //6.处理提现结果
//        //微信接口是否成功
//        if(!StringUtils.isEmpty(stringStringMap) && "SUCCESS".equals(return_code)){
//            //业务结果
//            if("SUCCESS".equals(result_code)){
//                //更新日志记录
//                updateAddAppWithdrawal(appUser, 2, "微信提现成功", "微信提现成功", partnerTradeNo, amount);
//                //公众号发送消息
//                try {
//                    String amount1 = amount + "元";
//                    ServerResponse<String> respone = sendCashMessage(appUser,"30001", appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(),amount1, "微信");
//                    log.info("公众号发消息结果{}",JSON.toJSONString(respone));
//                }catch (Exception e){
//                    log.info("公众号发消息异常{}",e.getMessage());
//                }
//                //用户账户余额信息（新增表,待处理）
//                return ServerResponse.createBySuccessMessage("微信提现成功");
//            }else{
//                String err_code = MapUtils.getString(stringStringMap, "err_code");
//                String err_code_des = MapUtils.getString(stringStringMap, "err_code_des");
//                log.info("微信提现业务失败状态码：{}",err_code);
//                //判断失败原因是否是公司账户余额不足
//                if("NOTENOUGH".equals(err_code)){
//                    //给帅帅发提示短信
//                    String phone = "18569966681";
//                    String content = "您的企业公众号付款帐号余额不足";
//                    String result = null;
//                    try {
//                        result = MessageUtils.sendMesage(phone, content);
//                    } catch (Exception e) {
//                        log.info("账户余额不足短信发送失败{}",result);
//                        e.printStackTrace();
//                    }
//                    log.info("账户余额不足短信发送结果{}",result);
//                }
//                //已经达到今日付款总额上限/已达到付款给此用户额度上限（设置一天一次）
//                if("SENDNUM_LIMIT".equals(err_code)){
//                    err_code_des = "24小时内仅限提现一次哦!";
//                }
//
//                //更新日志记录
//                updateAddAppWithdrawal(appUser, 3, "微信提现失败", err_code_des, partnerTradeNo, amount);
//                log.info("提现业务失败原因：{}",err_code_des);
//                //支付失败，手动抛出异常
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
//
//
//                return ServerResponse.createByErrorMessage(err_code_des);
//            }
//
//        }else{
//            //支付失败，手动抛出异常
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
//
//            String return_msg = MapUtils.getString(stringStringMap, "return_msg");
//            log.info("提现接口失败原因：{}",return_msg);
//            return ServerResponse.createByErrorMessage(return_msg);
//        }
//
//    }

    /**
     * 添加账户变更记录
     *
     * @param userid
     * @param amount
     */
    private void addSyserMoneyLog(SyUserMoney syUserMoney, Long userid, String amount) {

//        //获取用户账户
//        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userid);
        //变动前可用余额
        BigDecimal beforeBalance = syUserMoney.getCashBalanceAmount();
        log.info("用户userid:{}，账户变动前余额:{}", userid, beforeBalance);
        //提现金额
        BigDecimal amountDecimal = new BigDecimal(amount);
        log.info("用户userid:{}，提现金额:{}", userid, amount);
        //变动后可用余额
        BigDecimal afterBalance = beforeBalance.subtract(amountDecimal);
        log.info("用户userid:{}，变动后可用余额:{}", userid, afterBalance);

        SyUserMoneyLog syUserMoneyLog = new SyUserMoneyLog();
        syUserMoneyLog.setUserId(userid);
        syUserMoneyLog.setBeforeBalance(beforeBalance);
        syUserMoneyLog.setAmount(amountDecimal);
        syUserMoneyLog.setAfterBalance(afterBalance);
        syUserMoneyLog.setRemark("公众号提现");
        syUserMoneyLog.setLogStatus(1);//成功
        syUserMoneyLog.setLogType(1);//公众号

        syUserMoneyLogService.save(syUserMoneyLog);
    }

    /**
     * 校验金额
     * @param amount
     * @param userid
     * @return
     */
    private ServerResponse checkPayMoney(String amount, Long userid) {
        //校验金额不能为空
        if(StringUtils.isEmpty(amount)){
            log.info("校验》》金额不能为空！");
            return ServerResponse.createByErrorMessage("金额不能为空！");
        }
        //校验金额是否合法
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userid);
        if (syUserMoney == null){
            log.info("校验》》无可提现金额！");
            return ServerResponse.createByErrorMessage("无可提现金额！");
        }
        BigDecimal amountDecimal = new BigDecimal(amount);//提现金额
        log.info("用户userId：{}，提现金额为{}",userid,amount);
        BigDecimal cashBalanceAmount = syUserMoney.getCashBalanceAmount();//账户可提现金额
        log.info("用户userId：{}，微信提账户余额{}",userid,cashBalanceAmount);
        if(cashBalanceAmount.compareTo(new BigDecimal(0)) == -1){
            log.info("校验》》账户提现金额不足！");
            return ServerResponse.createByErrorMessage("账户提现金额不足！");
        }
        if (amountDecimal.compareTo(cashBalanceAmount) == 1){
            log.info("校验》》提现金额超出可提现！");
            return ServerResponse.createByErrorMessage("提现金额超出可提现！");
        }
        //校验金额是否与设置提现金额匹配
        log.info("提现金额{}",amount);
        if(amount.contains(".")){
            log.info("提现金额{}带有小数点",amount);
            return ServerResponse.createByErrorMessage("提现金额{}不合法!不能带小数点");

        }else{
            SyWithdrawalSetup syWithdrawalSetup = syWithdrawalSetupMapper.selectByPrimaryKey(1);
            if(syWithdrawalSetup != null){
                String fastWithdrawalAmounts = syWithdrawalSetup.getFastWithdrawalAmounts();
                if(!fastWithdrawalAmounts.contains(amount)){
                    log.info("校验1》》金额不能自定义！");
                    return ServerResponse.createByErrorMessage("金额不能自定义！");
                }
            }
        }
        return ServerResponse.createBySuccess("金额合法");
    }

    /**
     * 发起支付
     * @param amount
     * @param appUser
     * @param openid
     * @param type
     * @return
     */
   /* private ServerResponse handlerPayMoney(String amount, AppUser appUser,String openid,Integer type) throws Exception{
        //1.创建微信企业支付请求参数
        WxPayRequestParams wxPayRequestParams = new WxPayRequestParams();

        //2.填充请求参数
        BigDecimal bigDecimal1 = new BigDecimal(amount);
        BigDecimal multiply = bigDecimal1.multiply(new BigDecimal("100"));//金额单位为分
        wxPayRequestParams.setAmount(multiply.toString());//金额 *100
        wxPayRequestParams.setOpenid(openid);//用户的openid（从用户表中获取）
        //wxPayRequestParams.setRe_user_name("张三");//真实姓名（从用户表中获取）
        wxPayRequestParams.setDesc(type==1?"省鸭APP提现":"公众号提现");//企业付款备注
        String partnerTradeNo = creatPartnerTradeNo(appUser.getUserId(), amount);
        wxPayRequestParams.setPartner_trade_no(partnerTradeNo);//订单号

        //3.请求参数转成xml
        Map map = JSON.parseObject(JSON.toJSONString(wxPayRequestParams), HashMap.class);
        String xmlStr = WXPayUtil.generateSignedXml(map,WxWithdrawal.key);
        log.info("请求微信支付接口参数：{}",xmlStr);
        String uuid = UUIDUtils.getUUID();

        //4.调用支付接口
        String  wxPayResultXml = wxPayRequest.requestWithCert(WxWithdrawal.urlSuffix, uuid, xmlStr, true);
        log.info("请求微信支付接口结果{}"+wxPayResultXml);

        //5.格式化返回结果
        Map<String, String> stringStringMap =  WXPayUtil.xmlToMap(wxPayResultXml);
        String wxPayResultJson = JSON.toJSONString(stringStringMap);

        String return_code = MapUtils.getString(stringStringMap, "return_code");
        String result_code = MapUtils.getString(stringStringMap, "result_code");

        //6.处理提现结果
        //微信接口是否成功
        if(!StringUtils.isEmpty(stringStringMap) && "SUCCESS".equals(return_code)){
            //业务结果
            if("SUCCESS".equals(result_code)){
                //更新日志记录
                updateAddAppWithdrawal(appUser, 2, "微信提现成功", "微信提现成功", partnerTradeNo, amount);
                //公众号发送消息
                try {
                    String amount1 = amount + "元";
                    ServerResponse<String> respone = sendCashMessage(appUser,"30001", appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(),amount1, "微信");
                    log.info("公众号发消息结果{}",JSON.toJSONString(respone));
                }catch (Exception e){
                    log.info("公众号发消息异常{}",e.getMessage());
                }
                //用户账户余额信息（新增表,待处理）
                return ServerResponse.createBySuccessMessage("微信提现成功");
            }else{
                String err_code = MapUtils.getString(stringStringMap, "err_code");
                String err_code_des = MapUtils.getString(stringStringMap, "err_code_des");
                log.info("微信提现业务失败状态码：{}",err_code);
                //判断失败原因是否是公司账户余额不足
                if("NOTENOUGH".equals(err_code)){
                    //给帅帅发提示短信
                    String phone = "18569966681";
                    String content = "您的企业公众号付款帐号余额不足";
                    String result = null;
                    try {
                        result = MessageUtils.sendMesage(phone, content);
                    } catch (Exception e) {
                        log.info("账户余额不足短信发送失败{}",result);
                        e.printStackTrace();
                    }
                    log.info("账户余额不足短信发送结果{}",result);
                }
                //已经达到今日付款总额上限/已达到付款给此用户额度上限（设置一天一次）
                if("SENDNUM_LIMIT".equals(err_code)){
                    err_code_des = "24小时内仅限提现一次哦!";
                }

                //更新日志记录
                updateAddAppWithdrawal(appUser, 3, "微信提现失败", err_code_des, partnerTradeNo, amount);
                log.info("提现业务失败原因：{}",err_code_des);
                //支付失败，手动抛出异常
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误


                return ServerResponse.createByErrorMessage(err_code_des);
            }

        }else{
            //支付失败，手动抛出异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误

            String return_msg = MapUtils.getString(stringStringMap, "return_msg");
            log.info("提现接口失败原因：{}",return_msg);
            return ServerResponse.createByErrorMessage(return_msg);
        }

    }*/

    /**
     * 校验用户是否关注公众号和金额校验
     * @param amount
     * @param appUser
     * @return
     */
    private Object cheackUserAndAmount(String amount, AppUser appUser) {
        if(StringUtils.isEmpty(amount))return ServerResponse.createByErrorMessage("金额不能为空！");
        SyUserWxContrast syUserWxContrast = iSyUserWxContrastService.selectByUserId(appUser.getWechatUnionid());
        if(StringUtils.isEmpty(syUserWxContrast) || StringUtils.isEmpty(syUserWxContrast.getWxOpendId())){
            //增加提现记录 未处理的提现记录
            //addAppWithdrawal(appUser,amount,1,null,"未关注公众号提现",creatPartnerTradeNo(appUser.getUserId(),amount));
            return ServerResponse.createByErrorMessage("您未关注公众号！");
        }
        SyWithdrawalSetup syWithdrawalSetup = syWithdrawalSetupMapper.selectByPrimaryKey(1);
        if(syWithdrawalSetup != null){
            String fastWithdrawalAmounts = syWithdrawalSetup.getFastWithdrawalAmounts();
            if(!fastWithdrawalAmounts.contains(amount))return ServerResponse.createByErrorMessage("金额不能自定义！");
        }
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(appUser.getUserId());
        if (syUserMoney == null) return ServerResponse.createByErrorMessage("无可提现金额！");
        BigDecimal bigDecimal = new BigDecimal(amount);
        BigDecimal cashBalanceAmount = syUserMoney.getCashBalanceAmount();
        log.info("微信提现用户可提现金额{}",cashBalanceAmount);
        if (bigDecimal.compareTo(cashBalanceAmount) == 1) return ServerResponse.createByErrorMessage("提现金额超出可提现！");
        return syUserWxContrast.getWxOpendId();
    }

    /**
     * 生成商户订单号  年与日时分秒+用户id+金额
     * @return
     */
    private String creatPartnerTradeNo(Long userId,String amount){
        StringBuilder stringBuilder = new StringBuilder();
        Long dateStr = DateFormatUtils.dateToString(new Date(), "yyyyMMddHHmm");
        stringBuilder.append(dateStr);
        stringBuilder.append(userId);
        stringBuilder.append(amount);
        int length = 32 - stringBuilder.toString().length();
        stringBuilder.append(RandomStringUtils.randomNumeric(length));
        return stringBuilder.toString();
    }
    private void addAppWithdrawalNew(AppUser appUser, String  amount) {
//        //查询提现金额
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("user_id",appUser.getUserId());
//        queryWrapper.eq("applicant_status",1);
//        queryWrapper.eq("withdrawal_type",2);//微信
//        List<AppWithdrawal> appWithdrawalList = withdrawalService.list(queryWrapper);
//        if(CollectionUtils.isEmpty(appWithdrawalList)){

        AppWithdrawal appWithdrawal = new AppWithdrawal();
        appWithdrawal.setDeviceName("设备名称." + appUser.getUserId());
        appWithdrawal.setUserId(appUser.getUserId());
        appWithdrawal.setWechatNickname(appUser.getWechatNickname());
        appWithdrawal.setWechatId(appUser.getWechatUnionid());
        appWithdrawal.setApplicantStatus(1);
//        appWithdrawal.setProcessingResults("");
        appWithdrawal.setTransferState(2);
        appWithdrawal.setAmount(Double.valueOf(amount));
//        appWithdrawal.setRemark("提现记录");
        appWithdrawal.setApplicantTime(System.currentTimeMillis());
//        appWithdrawal.setProcessingTime(System.currentTimeMillis());
        appWithdrawal.setWithdrawalType(2);
//        appWithdrawal.setPartnerTradeNo(partnerTradeNo);
        int i = iAppWithdrawalService.insertAppWithdrawal(appWithdrawal);
        log.info("添加用户{}微信提现（app提现）记录",appUser.getUserId());

//        }

    }

    /**
     * @param appUser        用户
     * @param status         提现状态
     * @param result         处理结果
     * @param message        微信提现结果返回参数
     * @param partnerTradeNo 订单号
     */
    private void updateAddAppWithdrawal(AppUser appUser, Integer status, String result, String message, String partnerTradeNo, String amount) {
//            //查询提现金额
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id",appUser.getUserId());
//            queryWrapper.eq("applicant_status",1);
//            queryWrapper.eq("withdrawal_type",2);
//            List<AppWithdrawal> appWithdrawalList = withdrawalService.list(queryWrapper);
//            if(CollectionUtils.isNotEmpty(appWithdrawalList)){
//                AppWithdrawal withdrawal = appWithdrawalList.get(0);
//                //修改提现记录
//                AppWithdrawal appWithdrawal = new AppWithdrawal();
//                appWithdrawal.setId(withdrawal.getId());
//                appWithdrawal.setApplicantStatus(status);
//                appWithdrawal.setProcessingResults(result);
//                appWithdrawal.setRemark(message);
//                appWithdrawal.setWithdrawalType(2);
//                appWithdrawal.setPartnerTradeNo(partnerTradeNo);
//                appWithdrawal.setProcessingTime(System.currentTimeMillis());
//                boolean b = withdrawalService.updateById(appWithdrawal);
//                log.info("修改微信提现记录id:{}",withdrawal.getId());
//            }

        AppWithdrawal appWithdrawal = new AppWithdrawal();
        appWithdrawal.setDeviceName("设备名称." + appUser.getUserId());
        appWithdrawal.setUserId(appUser.getUserId());
        appWithdrawal.setWechatNickname(appUser.getWechatNickname());
        appWithdrawal.setWechatId(appUser.getWechatUnionid());
        appWithdrawal.setApplicantStatus(status);
        appWithdrawal.setProcessingResults(result);
        appWithdrawal.setRemark(message);
        ;
        appWithdrawal.setWithdrawalType(2);
        appWithdrawal.setPartnerTradeNo(partnerTradeNo);
        appWithdrawal.setProcessingTime(System.currentTimeMillis());
        appWithdrawal.setTransferState(2);
        appWithdrawal.setAmount(Double.valueOf(amount));
        appWithdrawal.setApplicantTime(System.currentTimeMillis());
        int i = iAppWithdrawalService.insertAppWithdrawal(appWithdrawal);
        log.info("添加用户{}微信提现（app提现）记录", appUser.getUserId());

    }
    //该接口支持到2.3.0以下
    private void addAppWithdrawal(AppUser appUser, String  amount, Integer status, String result, String message, String partnerTradeNo,AppWithdrawal appWithdrawal1) {
        try {
            if(!StringUtils.isEmpty(appWithdrawal1)){
                //修改提现记录
                AppWithdrawal appWithdrawal = new AppWithdrawal();
                appWithdrawal.setId(appWithdrawal1.getId());
                appWithdrawal.setApplicantStatus(status);
                appWithdrawal.setPartnerTradeNo(partnerTradeNo);
                appWithdrawal.setProcessingTime(System.currentTimeMillis());
                boolean b = withdrawalService.updateById(appWithdrawal);
                log.info("修改微信提现记录（公众号提现）是否成功:{}id:{}",b,appWithdrawal1.getId());

            }else{
                //新增提现记录
                AppWithdrawal appWithdrawal = new AppWithdrawal();
                appWithdrawal.setDeviceName("设备名称." + appUser.getUserId());
                appWithdrawal.setUserId(appUser.getUserId());
                appWithdrawal.setWechatNickname(appUser.getWechatNickname());
                appWithdrawal.setWechatId(appUser.getWechatUnionid());
                appWithdrawal.setApplicantStatus(status);
                appWithdrawal.setProcessingResults(result);
                appWithdrawal.setTransferState(2);
                appWithdrawal.setAmount(Double.valueOf(amount));
                appWithdrawal.setRemark(message);
                appWithdrawal.setApplicantTime(System.currentTimeMillis());
                appWithdrawal.setProcessingTime(System.currentTimeMillis());
                appWithdrawal.setWithdrawalType(2);
                appWithdrawal.setPartnerTradeNo(partnerTradeNo);
                int i = iAppWithdrawalService.insertAppWithdrawal(appWithdrawal);
                log.info("添加微信提现（app提现）记录是否成功{}", i);
            }
        } catch (Exception e) {
            log.info("新增/修改微信提现记录失败{}", e.getMessage());
        }

    }
    @Override
    public ServerResponse rules(Long userId) {
        SyWithdrawalSetup syWithdrawalSetup = syWithdrawalSetupMapper.selectByPrimaryKey(1);
        //根据用户id查询用户的微信可提现金额
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userId);
        BigDecimal cashBalanceAmount = new BigDecimal("0");
        BigDecimal cashTotalAmount = new BigDecimal("0");
        if(!StringUtils.isEmpty(syUserMoney)){
            cashBalanceAmount = syUserMoney.getCashBalanceAmount();
            cashTotalAmount = syUserMoney.getCashTotalAmount();
        }

        com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)com.alibaba.fastjson.JSONObject.toJSON(syWithdrawalSetup);
        Integer upcomingAccount = iAppUserRedRewardService.selectCountMoneyStatus(userId,2);
        //根绝用户id查询用户的 可提现 累计入账 即将到账
        jsonObject.put("Withdrawable", cashBalanceAmount);//可提现
        jsonObject.put("accumulatedEntry", cashTotalAmount);//累计入账
        jsonObject.put("upcomingAccount", upcomingAccount==null?0:upcomingAccount);//即将到账
        return ServerResponse.createBySuccess("数据获取成功", jsonObject);
    }

    @Override
    public ServerResponse gettransferinfo() {
        WxPayRequestParams wxPayRequestParams;
        try {
            wxPayRequestParams = new WxPayRequestParams();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("请求参数错误！");
        }
        //2.填充请求参数
        wxPayRequestParams.setPartner_trade_no("10000098201411111234567890");//订单号
        //3.请求参数转成xml
        String xmlStr;
        try {
            Map map = new HashMap();
            map.put("nonce_str", wxPayRequestParams.getNonce_str());
            map.put("sign", wxPayRequestParams.getSign());
            map.put("partner_trade_no", wxPayRequestParams.getPartner_trade_no());
            map.put("mch_id", wxPayRequestParams.getMchid());
            map.put("appid", wxPayRequestParams.getMch_appid());
            xmlStr = WXPayUtil.mapToXml(map);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("参数转换错误！");
        }
        String restTemplate = getRestTemplate("https://" + WxWithdrawal.doMain + WxWithdrawal.urlSuffixSelect, xmlStr);
        return null;
    }

    @Override
    public ServerResponse appWithdrawalList(int currentPage, int pageSize, Long userId, Integer withdrawalType) {
        return withdrawalService.selectAppWithdrawalList(currentPage,pageSize,null,withdrawalType,userId,2,null,null,null,null,null,null);
    }

    public static String getRestTemplate(String url, String params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> entity = new HttpEntity<String>(params, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return exchange.getBody();
    }

    /**
     * 发送模板消息
     * @param u
     * @param messageType
     * @param keyword1Param
     * @param keyword2Param
     * @param keyword3Param
     * @param keyword4Param
     * @return
     * @throws ParseException
     * @throws IOException
     */
    @Override
    public ServerResponse<String> sendCashMessage(AppUser u, String messageType, String keyword1Param, String keyword2Param, String keyword3Param, String keyword4Param) throws ParseException, IOException {

        if (null == u) {
            return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
        }
        log.info("该用户unionId:" + u.getWechatUnionid());

        //获取openId
        QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id", u.getWechatUnionid());
        queryWrapper.eq("enable", true);
        queryWrapper.eq("deleted", false);
        List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);
        SyUserWxContrast contrast = null;
        String openId = "";
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(listWxContrast)) {
            //已经关注公众号，返回提示
            openId = listWxContrast.get(0).getWxOpendId();
        }

        //校验参数
        if (openId == null || "".equals(openId)) {
            return ServerResponse.createByErrorMessage("该用户未关注公众号:" + u.getUserId());
        }
        if (messageType == null) {
            return ServerResponse.createByErrorMessage("参数不能为空:" + messageType);
        }

        String accessToken = getAccessToken();
        //区分消息模板id
        String templateId = "";
        String firstParam = "";
        String remarkParam = "";
        Integer newsType = null;
        if("30001".equals(messageType)){
            templateId = WechatConfig.ARRIVAL_ACCOUNT_TEMPLATE_ID;//提现到账通知
            firstParam = "你好，您已成功提现";
            remarkParam = "详情请进入省鸭App中查看";
            //remarkParam = "现金已成功到账您的微信钱包，详情查看《我》-《钱包》-《零钱明细》";
            newsType = NewsEnumLog.NEWS_ARRIVAL_ACCOUNT.getNewsType();
        }
        if("30002".equals(messageType)){
            templateId = WechatConfig.CHECKOUT_SUCCESS_TEMPLATE_ID;//下单成功提醒
            firstParam = "下单成功";
            remarkParam = "此次帮您节省" + keyword4Param + "元";
            newsType = NewsEnumLog.NEWS_CHECKOUT_SUCCESS.getNewsType();
        }
        if("30003".equals(messageType)){
            templateId = WechatConfig.SUCCESSFUL_DELIVERY_TEMPLATE_ID;//收货成功提醒
            firstParam = "收货成功提醒";
            remarkParam = "冻结补贴" + keyword4Param + "元";
            newsType = NewsEnumLog.NEWS_SUCCESSFUL_DELIVERY.getNewsType();
        }
        if("30004".equals(messageType)){
            templateId = WechatConfig.FRIENDS_SUCCEED_TEMPLATE_ID;//好友下单成功提醒
            firstParam = "好友下单成功";
            remarkParam = "详情请进入省鸭App中查看";
            newsType = NewsEnumLog.NEWS_FRIENDS_SUCCEED.getNewsType();
        }

        if("30005".equals(messageType)){
            templateId = WechatConfig.INVITE_FRIENDS_TEMPLATE_ID;//邀请好友成功
            firstParam = "邀请好友成功";
            remarkParam = "详情请进入省鸭App中查看";
            newsType = NewsEnumLog.NEWS_INVITE_FRIENDS.getNewsType();
        }

        if("30006".equals(messageType)){
            templateId = WechatConfig.SUBSIDY_ARRIVAL_TEMPLATE_ID;//补贴到账通知
            firstParam = "补贴到账";
            remarkParam = "详情请进入省鸭App中查看";
            newsType = NewsEnumLog.NEWS_SUBSIDY_ARRIVAL.getNewsType();
        }

        if ("".equals(templateId)) {
            return ServerResponse.createByErrorMessage("传入的模板类型不存在！");
        }
        if (newsType == null) {
            return ServerResponse.createByErrorMessage("未匹配到消息类型！");
        }
        //组装数据发送消息
        log.info("用户openId{},消息模板id{},消息头{}，消息体1{}，消息体2{}，消息体3{}，消息体4{}，消息尾{}", openId, templateId, firstParam, keyword1Param, keyword2Param, keyword3Param, keyword4Param, remarkParam);
        Map<String, String> map = WeixinUtil.handleMessage(accessToken, openId, templateId, firstParam, keyword1Param, keyword2Param, keyword3Param, keyword4Param, remarkParam);
        String newsContent = map.get("newsContent");//消息内容
        String aBoolean = map.get("result");//消息结果
        log.info("消息内容{}，消息结果{}", newsContent, aBoolean);
        //日志记录（2.3.1废弃）
//        AppNewsLog log = new AppNewsLog();
//        log.setUserId(u.getUserId());
//        log.setNewsTitle(firstParam);
//        log.setNewsContent(newsContent);
//        log.setNewsType(newsType);
//        log.setCreateTime(System.currentTimeMillis());
//        log.setUpdateTime(System.currentTimeMillis());
//        appNewsLogService.save(log);

        return ServerResponse.createBySuccess("消息发送结果", "true".equals(aBoolean) ? "成功" : "失败");
    }

    /**
     * 生成提现日志
     * @param appUser  用户信息
     * @param amount  提现金额
     * @param status  状态
     * @param result  结果
     * @param message  消息提示
     * @return
     */
    @Override
    public int addLogAppWithdrawal(AppUser appUser, String amount, int status,  String result, String message) {
        log.info("开始添加微信提现记录");
        //生成订单号
//		String partnerTradeNo = creatPartnerTradeNo(appUser.getUserId(), amount);
        //新增提现记录
        AppWithdrawal appWithdrawal = new AppWithdrawal();
        appWithdrawal.setDeviceName("设备名称." + appUser.getUserId());
        appWithdrawal.setUserId(appUser.getUserId());
        appWithdrawal.setWechatNickname(appUser.getWechatNickname());
        appWithdrawal.setWechatId(appUser.getWechatUnionid());
        appWithdrawal.setApplicantStatus(status);
        appWithdrawal.setProcessingResults(result);
        appWithdrawal.setTransferState(2);
        appWithdrawal.setAmount(Double.valueOf(amount));
        appWithdrawal.setRemark(message);
        appWithdrawal.setApplicantTime(System.currentTimeMillis());
        appWithdrawal.setProcessingTime(System.currentTimeMillis());
        appWithdrawal.setWithdrawalType(2);
        appWithdrawal.setPartnerTradeNo(null);
        int i = iAppWithdrawalService.insertAppWithdrawal(appWithdrawal);
        log.info("添加微信提现记录成功{}", i);
        return i;
    }

    /**
     *
     * @param toUserName  开发者微信号
     * @param openId  收到的OpenID
     * @param msgId  收到的消息id
     * @return
     * @throws IOException
     */
    @Override
    public String getResponseMessage(String toUserName, String openId,String msgId) throws Exception {
        log.info("进入支付方法");
        String mycontent = null;//消息内容
        String message = null;//消息的xml字符串
        //获取accessToken
        String accessToken = getAccessToken();
        //查询unionId
        net.sf.json.JSONObject userInfo = WeixinUtil.getUserInfo(accessToken, openId);
        String unionid = userInfo.getString("unionid");
        log.info("用户的unionId:" + unionid );

        //查询用户openId是否已经存在
        QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id",unionid);
        queryWrapper.eq("enable",true);
        queryWrapper.eq("deleted",false);
        List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);
        SyUserWxContrast contrast = null;
        if (CollectionUtils.isEmpty(listWxContrast)){
            //保存用户信息（unionId，appOpenId)
            log.info("保存用户openId信息" );
            contrast = new SyUserWxContrast();
            contrast.setUnionId(unionid);
            contrast.setWxOpendId(openId);
            syUserWxContrastService.save(contrast);
        }
        //查询用户userId，通过unionId
        log.info("查询用户userId，通过unionId");
        QueryWrapper<AppUser> queryUser= new QueryWrapper<>();
        queryUser.eq("wechat_unionid",unionid);
        queryUser.eq("enable",true);//是否启用
        List<AppUser> listUser = appUserService.list(queryUser);
        //判断是否使用app进行授权
        if(CollectionUtils.isEmpty(listUser)){
            log.info("未使用app进行授权");
            mycontent = menuText(2);
            message = WeixinUtil.initText(toUserName, openId, mycontent,msgId);
        }else{
            //查询日志，（userId,未处理），返回金额
            log.info("开始判断是否可以提现的逻辑");
            AppUser appUser = listUser.get(0);
            QueryWrapper<AppWithdrawal> query= new QueryWrapper<>();
            query.eq("user_id",appUser.getUserId());
            query.eq("applicant_status",1);
            List<AppWithdrawal> list = iAppWithdrawalService.list(query);
            if(CollectionUtils.isEmpty(list)){
                log.info("请先到省鸭app提现中选择金额");
                mycontent = menuText(3);
                message = WeixinUtil.initText(toUserName, openId, mycontent,msgId);
            }else{
                //发起支付处理，返回支付结果
                AppWithdrawal appWithdrawal = list.get(0);
                int intValue = appWithdrawal.getAmount().intValue();
                ServerResponse serverResponse = toGet(String.valueOf(intValue), appWithdrawal.getUserId(), 2);
                log.info("接收公众号提現的结果{}",JSON.toJSONString(serverResponse));
                //发送消息
                if(200 == serverResponse.getStatus()){
                    log.info("提现成功");
                    mycontent = menuText(1);
                    message = WeixinUtil.initText(toUserName, openId, mycontent,msgId);
                }else{
                    log.info("提现失败");
                    log.info(serverResponse.getMsg());
                    mycontent = menuText(4);
//                        mycontent = serverResponse.getMsg();
                    message = WeixinUtil.initText(toUserName, openId, mycontent,msgId);
                }
            }
        }
        log.info("提现服务返回的信息{}",message);
        return message;
    }


    /**
     * 关注公众号发送的消息
     * @param type (0:关注发送消息；1：提现发送消息；2：提现授权登陆；3.提示择金额提示；4.提现失败)
     * @return
     */
    public static String menuText(int type){
        StringBuffer sb = new StringBuffer();
        if(0 == type){
            sb.append("欢迎关注~\n");
            sb.append("首次提现需点击下方菜单栏“提现”按钮，即可到账呦！");
        }
        if(1 == type){
            sb.append("提现成功~\n");
            sb.append("请到零钱中查看！");
        }
        if(2 == type){
            sb.append("提现失败~\n");
//            sb.append("请先下载省鸭app，进行授权！");
            sb.append("请先到省鸭app发起提现!");
        }
        if(3 == type){
            sb.append("提现失败~\n");
//            sb.append("请先到省鸭app提现中选择金额！");
            sb.append("请先到省鸭app发起提现!!");
        }
        if(4 == type){
            sb.append("提现失败~\n");
            sb.append("提现失败，请联系省鸭App客服！");
        }
        return sb.toString();
    }


    /**
     * 微信提现判断是否为黑名单用户如果是黑名单用户 1 新增一条未处理的提现记录
     * @return
     * @param appUser
     * @param amount
     */
    private boolean checkBlacklist(AppUser appUser, String amount){
        Long userId = appUser.getUserId();
        if(iSyBlacklistService.userCheck(userId,appUser.getSuperInviteCode())){
            log.info("黑名单用户提现用户id{}金额{}",userId,amount);
            int i = iSyUserMoneyService.wxPaySuccessUpdate(userId,amount);
            log.info("更新用户（黑名单用户）金额表微信可提现结果{}用户id{}金额{}",i,userId,amount);
            addAppWithdrawal(appUser,amount,1,null,"app提现：黑名单用户提现",creatPartnerTradeNo(userId, amount),null);
            return true;
        }
        return false;
    }
}
